<template>
  <!--    :class="mode !== 'single'?'large-modal':'normal-modal'"  -->
  <a-modal
    title="物料选择"
    class="large-modal"
    centered
    :visible="visible"
    :ok-text="isDownload ? '选中导出' : '选中提交'"
    :confirm-loading="loading"
    @ok="handleOk"
    @cancel="visible = false"
  >
    <a-row :gutter="20">
      <a-col
        v-if="mode !== 'single'"
        span="6"
        class="goods-search-left"
      >
        <a-card :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 180px); overflow: auto'">
          <title-name title="物资目录" />
          <a-input-search
            style="margin-bottom: 8px"
            @change="onChange"
          />
          <a-tree
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :selected-keys.sync="treeSelectedKeys"
            :load-data="getTree"
            @select="onSelect"
            @expand="onExpand"
          >
            <template
              slot="title"
              slot-scope="{ title }"
            >
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </a-card>
      </a-col>
      <a-col :span="mode === 'single' ? 24 : 18">
        <searchData ref="searchData" :search-data="defaultSearchList" @search="search" @reset="search" />
        <a-tag
          v-for="(item, index) of selectedRows"
          :key="item.id"
          :closable="!item.disabled"
          class="mb10p"
          color="#108ee9"
          @close="close(index)"
        >
          {{ item[outTableDataMaterialKey[1]] }}
        </a-tag>
        <a-card>
          <b-table
            ref="table"
            :select-config="{ use: true, type: 'checkbox', rowKey }"
            :scroll="{ x: 1200 }"
            :columns="localColumns"
            :request="loadData"
            :out-selected-row-keys="selectedKeys"
            @select-click="selectClick"
          />
        </a-card>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
import { findCatalogByTree, findListAddByMain } from '@/api/material/goods/goods'
import { mapGetters } from 'vuex'
// this.$emit('createList', this.selectedRows),会返回选中的数组
export default {
  name: 'MaterialListAndDir',
  props: {
    //已添加的数据的物资名称和物料编码
    outTableDataMaterialKey: {
      type: Array,
      default() {
        return ['materialCode', 'materialName']
      }
    },
    //模式，tree or single
    mode: {
      type: String,
      default: 'tree'
    },
    rowKey: {
      type: String,
      default: 'code'
    },
    //表格请求api
    api: {
      type: [Object, Function],
      default: () => findListAddByMain
    },
    // 请求参数
    requestParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rowConfig: {
      type: Object,
      default: () => {
        return {
          key: 'code',
          name: 'name'
        }
      }
    },
    // 表头
    localColumns: {
      type: [Object, Array],
      default: () => {
        return [
          {
            title: '物料名称',
            dataIndex: 'name'
          },
          {
            title: '物料编码',
            dataIndex: 'code',
            width: 130
          },
          {
            title: '物资目录名称',
            dataIndex: 'catalogName',
            width: 130
          },
          {
            title: '物资目录编码',
            dataIndex: 'catalogCode',
            width: 130
          },
          {
            title: '规格型号',
            dataIndex: 'specificationModel'
          },
          {
            title: '计量单位',
            dataIndex: 'unit',
            width: 100
          },
          {
            title: '状态',
            dataIndex: 'commonStatusStr',
            width: 80
          }
        ]
      }
    },
    // 搜索项配置
    localSearchArr: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      visible: false,
      queryParams: {},
      loadData: async (params) => {
        let searchData = Object.assign({}, params, this.queryParams, { commonStatus: 1 })
        if (searchData.catalogCode) {
          this.treeSelectedKeys = []
        }
        if (this.treeSelectedKeys.length) {
          searchData.catalogCode = this.catalogCode
        }
        // 添加额外参数
        if (Object.keys(this.requestParams)?.length > 0) {
          searchData = Object.assign({}, searchData, this.requestParams)
        }

        let res = await this.api(searchData)
        if (res.code === this.SUCCESS_CODE) {
          for (let i = 0; i < res.data.length; i++) {
            let v = res.data[i]
            let isSelect = this.outTableData.find(
              (w) => w[this.outTableDataMaterialKey[0]] === v[this.rowConfig.key]
            )
            if (isSelect) {
              v.disabled = true
            }
          }
          return { data: res.data, ...res }
        }
        return { data: [], code: 200 }
      },
      treeSelectedKeys: [],
      selectedKeys: [],
      selectedRows: [],
      treeData: [],
      catalogCode: null,
      replaceFields: {
        children: 'children',
        title: 'mateClassName',
        key: 'mateClassSysNo'
      },

      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataList: [],

      outTableData: [],
      isDownload: false,
      downloadApi: false,
      downloadApiArgs: null
    }
  },
  computed: {
    ...mapGetters(['GET_REDRESS_PERCENTAGE']),
    // 默认弹窗搜索配置项
    defaultSearchList() {
      let defaultList = [
        {
          name: '物料名称',
          value: this.rowConfig.name,
          type: 'input'
        },
        {
          name: '物料编码',
          value: this.rowConfig.key,
          type: 'input'
        },
        {
          name: '物资目录名称',
          value: 'catalogName',
          type: 'input'
        },
        {
          name: '物资目录编码',
          value: 'catalogCode',
          type: 'input'
        },
        {
          name: '规格型号',
          value: 'specificationModel',
          type: 'input'
        }
      ]
      console.log(this.localSearchArr.length)
      console.log(this.localSearchArr.length > 0 ? this.localSearchArr : defaultList)
      return this.localSearchArr.length > 0 ? this.localSearchArr : defaultList
    }
  },
  mounted() {
    this.mode === 'tree' && this.getTree()
  },
  methods: {
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange(e) {
      const value = e.target.value
      const expandedKeys = this.dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
      // console.log(expandedKeys)
      // console.log(this.searchValue)
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.key
        const title = node.title
        // this.dataList.push({ key, title: key })
        this.dataList.push({ key, title })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.key === key)) {
            parentKey = node.key
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },
    download(list, api, args = null) {
      this.open(list)
      this.isDownload = true
      this.downloadApi = api
      this.downloadApiArgs = args
    },
    close(index) {
      let item = this.selectedRows[index]
      // this.$console(item)
      let resIndex = this.selectedKeys.findIndex((v) => v === item[this.outTableDataMaterialKey[0]])
      if (resIndex !== -1) {
        this.selectedKeys.splice(resIndex, 1)
      }
      this.selectedRows.splice(index, 1)
    },
    selectClick(e) {
      let { rows, keys } = e
      let temp = []
      rows.map((v) => {
        let res = this.selectedRows.find((w) => v[this.rowConfig.key] === w[this.outTableDataMaterialKey[0]])
        if (!res) {
          v[this.outTableDataMaterialKey[0]] = v[this.rowConfig.key]
          v[this.outTableDataMaterialKey[1]] = v[this.rowConfig.name]
          temp.push(v)
        }
      })
      this.selectedRows = this.selectedRows.concat(temp)
      this.selectedRows = this.selectedRows.filter((v) => {
        return keys.find((w) => w === v[this.outTableDataMaterialKey[0]])
      })
      this.selectedKeys = keys
    },
    async getTree(treeNode) {
      return new Promise(async (resolve) => {
        let sysNo = 0
        if (treeNode) {
          if (treeNode.dataRef.children) {
            resolve()
            return
          }
          sysNo = treeNode.eventKey
        }
        let res = await findCatalogByTree({ sysNo })
        if (res.code === this.SUCCESS_CODE) {
          res.data = res.data.map((v) => {
            v.scopedSlots = { title: 'title' }
            v.key = v[this.replaceFields.key]
            v.title = v[this.replaceFields.title]
            return v
          })
          if (sysNo === 0) {
            this.treeData = res.data
          } else {
            treeNode.dataRef.children = res.data
            this.treeData = [...this.treeData]
          }
          this.generateList(this.treeData)
        }
        resolve()
      })
    },
    onSelect(selectedKeys, info) {
      this.treeSelectedKeys = selectedKeys
      if (selectedKeys.length) {
        this.catalogCode = info.selectedNodes[0].data.props.mateClassCode
      } else {
        this.catalogCode = null
      }
      this.$refs.searchData.resetFormItem('catalogCode')
      this.queryParams.catalogCode = void 0
      this.$refs.table.getData(null, true)
    },
    open(list) {
      this.isDownload = false
      this.loading = false
      this.visible = true
      this.outTableData = list ? this.$clone(list) : []
      // console.log(this.outTableData)
      this.selectedKeys = this.outTableData.map((v) => v[this.outTableDataMaterialKey[0]])
      this.selectedRows = this.outTableData.map((v) => {
        v.disabled = true
        return v
      })
      this.search()
    },
    async handleOk() {
      console.log(this.selectedRows)
      if (this.selectedRows.length === null) {
        return this.$noticeWarning('请选择数据')
      }
      if (this.selectedRows.length === this.outTableData.length) {
        return this.$noticeWarning('请选择数据')
      }
      let temp = []
      temp = this.selectedRows.filter((v) => {
        return !this.outTableData.find(
          (w) => w[this.outTableDataMaterialKey[0]] === v[this.outTableDataMaterialKey[0]]
        )
      })

      if (this.isDownload) {
        this.loading = true
        await this.downloadApi(temp, this.downloadApiArgs)
      } else {
        this.$emit('createList', temp)
      }
      this.visible = false
    },
    search(val) {
      this.queryParams = val || {}
      this.$refs.table && this.$refs.table.getData(null, true)
    }
  }
}
</script>
